//
//  SBSleepScrollView.m
//  TYCyclePagerViewDemo
//
//  Created by 黄建华 on 2018/1/16.
//  Copyright © 2018年 tany. All rights reserved.
//

#import "SBSleepScrollView.h"

#define SSWIDTH  [UIScreen mainScreen].bounds.size.width
#define SSHEIGHT [UIScreen mainScreen].bounds.size.height
@implementation SBSleepScrollView

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self creatView];
    }
    return self;
}

- (void)creatView {
    NSArray *array = @[KcolorHex(0x6b3895), KcolorHex(0x8073c8), KcolorHex(0xb6bbe4)];
    NSArray *titleArray = @[SN_Text(@"深睡"),SN_Text(@"浅睡"),SN_Text(@"清醒")];
    for (int i = 0; i <3; i ++) {
        UIView *view = [[UIView alloc] init];
        view.frame = SNFRAME(screenWidth/2 + 20 + (screenWidth/6)*i, 15, 15, 15);
        view.backgroundColor = [array objectAtIndex:i];
        [self addSubview:view];
        
        UILabel *label = [[UILabel alloc] init];
        label.textColor = [UIColor blackColor];
        label.font = SNFONT(10.0);
        label.adjustsFontSizeToFitWidth = YES;
        label.frame = SNFRAME(view.centerX - 30, view.bottom +10, 60, 20);
        label.textAlignment = NSTextAlignmentCenter;
        label.text = [titleArray objectAtIndex:i];
        [self addSubview:label];
    }
    
    NSMutableArray *sportArray = [NSMutableArray array];
    for (int i = -29; i <= 0; i++) {
        NSString            *lastStr = [[[NSDate date] dateAfterDay:i] dateToDayString];
        NSMutableDictionary *dic1    = [NSMutableDictionary dictionary];
        [dic1 setObject:StrByInt(0) forKey:@"deeps"];
        [dic1 setObject:StrByInt(0) forKey:@"lights"];
        [dic1 setObject:StrByInt(0) forKey:@"sobers"];
        [dic1 setObject:lastStr forKey:@"datestring"];
        [sportArray addObject:dic1];
    }
    _datas = [NSMutableArray arrayWithArray:sportArray];
    [self addPagerView];
    [self layoutSubviews];
    [_pagerView reloadData];
    [self updateScrollViewLabel];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUpdatePageViewInit) object:nil];
    [self performSelector:@selector(delayUpdatePageViewInit) withObject:nil afterDelay:0.05];
}

- (void)delayUpdatePageViewInit {
    _currentMoveIndex = 30 - 1;
    [_pagerView scrollToItemAtIndex:_currentMoveIndex animate:NO];
    [self updateLabelValue:_currentMoveIndex];
}

// 数据更新
- (void)loadDataWithModel:(FriendModel *)model {
    NSArray *array = [NSArray arrayWithArray:model.sleepHistory];
    for (int i = 0; i <_datas.count; i++) {
        NSDictionary * localDic = [_datas objectAtIndex:i];
        NSString *localDicDateString = localDic[@"datestring"];
        
        for (NSDictionary *dic in array) {
            NSString *dicDateString = dic[@"datestring"];
            if ([localDicDateString isEqualToString:dicDateString]) {
                [_datas replaceObjectAtIndex:i withObject:dic];
                break;
            }
        }
    }

    [self addPagerView];
    [self layoutSubviews];
    [_pagerView reloadData];
    [self updateScrollViewLabel];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUpdatePageViewInit) object:nil];
    [self performSelector:@selector(delayUpdatePageViewInit) withObject:nil afterDelay:0.05];
}

// 30天日期
- (void)updateScrollViewLabel {
    
    NSMutableArray *dateArray = [[NSMutableArray alloc] init];
    
    [dateArray addObject:@""];
    [dateArray addObject:@""];
    [dateArray addObject:@""];
    for (int i = -29; i <= 0; i++) {
        NSString *lastStr = [[[NSDate date] dateAfterDay:i] dateMonthAndDay];
        [dateArray addObject:lastStr];
    }
    [dateArray addObject:@""];
    [dateArray addObject:@""];
    [dateArray addObject:@""];
    
    for (int i = 0; i < dateArray.count; i++) {
        NSString *date   = [dateArray objectAtIndex:i];
        UIButton *button = [[UIButton alloc] init];
        button.tag             = 100+i;
        button.backgroundColor = [UIColor colorFromHex:0xd7d8d9];
        //日期不要年
        [button setTitle:date forState:UIControlStateNormal];
        button.titleLabel.font = SNFONT(13);
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
        
        button.frame = SNFRAME(screenWidth/7.0 *i, 0, screenWidth / 7.0, 40);
        [_labelScrollView addSubview:button];
        if (date.length > 0) {
            [button addTarget:self action:@selector(buttonLabelClick:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    CGFloat width = dateArray.count / 7 * screenWidth + (dateArray.count) %7 * screenWidth/7;
    _labelScrollView.decelerationRate = 0.9;
    _labelScrollView.contentSize      = CGSizeMake(width, 0);
    _labelScrollView.contentOffset    = CGPointMake(width, 0);
    _updateIndex                      = 29;
}

// 更新卡路里 距离
- (void)updateLabelValue:(NSInteger)selectIndex {
    NSDictionary *dic     = [NSDictionary dictionary];
    if (selectIndex < _datas.count) {
        dic = [_datas objectAtIndex:selectIndex];
    }
    NSInteger    deeps = [dic[@"deeps"]integerValue];
    NSInteger    lights    = [dic[@"lights"]integerValue];
    NSInteger    sobers    = [dic[@"sobers"]integerValue];

    NSInteger sleepTotal = deeps + lights + sobers;
    NSInteger efeTotal = deeps + lights;
    float value = 1.0 *efeTotal / sleepTotal;
    NSString *quality = [SleepModel WithQuality:value];
    if (sleepTotal == 0) {
        quality = SN_Text(@"暂无数据");
    }
    
    _calorLabel.text = [NSString stringWithFormat:@"%d%@ %d%@",efeTotal/60,SN_Text(@"h"),efeTotal%60,SN_Text(@"m")];
    
    _distanceLabel.text = quality;
    
    [_calorLabel setAttributedText:[SN_PublicClass label1With:_calorLabel.text withFontsize:12.0 withChangeText1:SN_Text(@"h") withChangeText2:SN_Text(@"m")]];
}

//更新UI
- (void)buttonTitleUpdate:(NSInteger)selectIndex {
    for (UIButton *button in _labelScrollView.subviews) {
        if ([button isKindOfClass:[UIButton class]]) {
            if (button.tag -100 -3 == selectIndex) {
                button.selected = YES;
                NSString *titleString = button.titleLabel.text;
                _dateLabel.text = titleString;
            } else {
                button.selected = NO;
            }
        }
    }
    [self updateLabelValue:selectIndex];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGFloat   width = screenWidth/ 7.0;
    NSInteger index = (NSInteger)((_labelScrollView.contentOffset.x+10)/width);
    
    [_labelScrollView setContentOffset:CGPointMake(width*index*1.0, 0) animated:YES];
    [self buttonTitleUpdate:index];
    [self labelControlWith:index];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    CGFloat   width = screenWidth/ 7.0;
    NSInteger index = (NSInteger)((_labelScrollView.contentOffset.x+10)/width);
    
    [_labelScrollView setContentOffset:CGPointMake(width*index*1.0, 0) animated:YES];
    [self buttonTitleUpdate:index];
    [self labelControlWith:index];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat   width = screenWidth/ 7.0;
    NSInteger index = (NSInteger)((_labelScrollView.contentOffset.x+10)/width);
    
    _updateIndex = index;
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUPdateButton) object:nil];
    [self performSelector:@selector(delayUPdateButton) withObject:nil afterDelay:0.02];
    [self labelControlWith:index];
}

- (void)delayUPdateButton {
    for (UIButton *button in _labelScrollView.subviews) {
        if ([button isKindOfClass:[UIButton class]]) {
            if (button.tag -100 -3 == _updateIndex) {
                button.selected = YES;
                NSString *titleString = button.titleLabel.text;
                _dateLabel.text = titleString;
            } else {
                button.selected = NO;
            }
        }
    }
}

- (void)buttonLabelClick:(UIButton *)sender {
    CGFloat   width = screenWidth/ 7.0;
    NSInteger index = sender.tag - 100-3;
    
    [_labelScrollView setContentOffset:CGPointMake(width*index*1.0, 0) animated:YES];
    
    [self buttonTitleUpdate:index];
    [self labelControlWith:index];
}

// label控制圆圈
- (void)labelControlWith:(NSInteger)selectIndex {
    _pagerView.delegate = nil;
    [_pagerView scrollToItemAtIndex:selectIndex animate:YES];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUPdatePageView) object:nil];
    [self performSelector:@selector(delayUPdatePageView) withObject:nil afterDelay:0.25];
}

- (void)delayUPdatePageView {
    _pagerView.delegate = self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _pagerView.frame              = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    _pagerView.layout.itemSize    = CGSizeMake(self.frame.size.width /3 *0.85, self.frame.size.width /3 *0.85);
    _pagerView.layout.itemSpacing = 15;
    _pagerView.layout.layoutType  = TYCyclePagerTransformLayoutLinear;
    [_pagerView setNeedUpdateLayout];
    
    _labelScrollView.frame                          = SNFRAME(0, _pagerView.height - 80, _pagerView.width, 40);
    _labelScrollView.delegate                       = self;
    _labelScrollView.showsHorizontalScrollIndicator = NO;
    _labelScrollView.showsVerticalScrollIndicator   = NO;
    
    _imageV.frame = SNFRAME(10, 10, 50, 50);
    _imageV.image = [UIImage image:@"F睡眠"];
    
    _type.textColor = [UIColor blackColor];
    _type.frame     = SNFRAME(_imageV.right + 10, _imageV.top + 7, 100, 20);
    _type.font      = SNFONT(16.0);
    _type.text      = SN_Text(@"睡眠");
    
    _dateLabel.textColor = SNCOLORGRAYLINE;
    _dateLabel.frame     = SNFRAME(_imageV.right + 10, _type.bottom, 100, 20);
    _dateLabel.font      = SNFONT(13.0);
    
    _imageV1.frame = SNFRAME(5, _pagerView.height - 35, 30, 30);
    _imageV1.image = [UIImage image:@"时间"];
    
    _info1.textColor = SNCOLORGRAY;
    _info1.text      = SN_Text(@"有效睡眠时长");
    _info1.frame     = SNFRAME(_imageV1.right, _imageV1.top +5, screenWidth/4 -_imageV1.right + 40, 20);
    _info1.font      = SNFONT(12.0);
    
    _calorLabel.textColor = SNCOLORBLACK;
    _calorLabel.text      = @"";
    _calorLabel.textAlignment = NSTextAlignmentCenter;
    _calorLabel.frame     = SNFRAME(_info1.right , _imageV1.top +5, 60, 20);
    _calorLabel.font      = SNFONT(14.0);
    
    float adOX = _calorLabel.right;
    if(adOX < screenWidth/2.0)
    {
        adOX = screenWidth/2.0;
    }
    
    _imageV2.frame = SNFRAME(adOX , _pagerView.height - 35, 30, 30);
    _imageV2.image = [UIImage image:@"睡眠质量"];
    
    _info2.textColor = SNCOLORGRAY;
    _info2.text      = SN_Text(@"睡眠质量");
    _info2.frame     = SNFRAME(_imageV2.right, _imageV2.top +5,50, 20);
    _info2.font      = SNFONT(12.0);
    
    _distanceLabel.textColor = SNCOLORBLACK;
    _distanceLabel.text      = @"";
    _distanceLabel.frame     = SNFRAME(_info2.right, _imageV2.top +5,screenWidth - _info2.right -2, 20);
    _distanceLabel.font      = SNFONT(14.0);
    _distanceLabel.textAlignment = NSTextAlignmentCenter;
    
    _type.adjustsFontSizeToFitWidth = YES;
    _type.minimumScaleFactor = 0.6;
    _info1.adjustsFontSizeToFitWidth = YES;
    _info1.minimumScaleFactor = 0.6;
    _info2.adjustsFontSizeToFitWidth = YES;
    _info2.minimumScaleFactor = 0.6;
    _calorLabel.adjustsFontSizeToFitWidth = YES;
    _calorLabel.minimumScaleFactor = 0.6;
    _distanceLabel.adjustsFontSizeToFitWidth = YES;
    _distanceLabel.minimumScaleFactor = 0.6;
}

- (void)addPagerView {
    if (_pagerView) {
        _pagerView.delegate = nil;
        [_pagerView removeFromSuperview];
        _pagerView = nil;
    }
    
    _pagerView                   = [[TYCyclePagerView alloc]init];
    _pagerView.layer.borderWidth = 1;
    _pagerView.layer.borderColor = SNCOLORGRAYLINE.CGColor;
    _pagerView.dataSource        = self;
    _pagerView.delegate          = self;
    // registerClass or registerNib
    [_pagerView registerClass:[SleepTYCyclePagerViewCell class] forCellWithReuseIdentifier:@"sleeppagerViewcellId"];
    [self addSubview:_pagerView];
    // 是否无限滚
    _pagerView.isInfiniteLoop              = NO;
    _pagerView.autoScrollInterval          = 0;
    _pagerView.layout.itemHorizontalCenter = YES;
    
    _imageV = [[UIImageView alloc] init];
    [_pagerView addSubview:_imageV];
    
    _type = [[UILabel alloc] init];
    [_pagerView addSubview:_type];
    
    _dateLabel = [[UILabel alloc] init];
    [_pagerView addSubview:_dateLabel];
    
    _labelScrollView = [[UIScrollView alloc] init];
    [_pagerView addSubview:_labelScrollView];
    
    _imageV1 = [[UIImageView alloc] init];
    [_pagerView addSubview:_imageV1];
    
    _info1 = [[UILabel alloc] init];
    [_pagerView addSubview:_info1];
    
    _calorLabel = [[UILabel alloc] init];
    [_pagerView addSubview:_calorLabel];
    
    _imageV2 = [[UIImageView alloc] init];
    [_pagerView addSubview:_imageV2];
    
    _info2 = [[UILabel alloc] init];
    [_pagerView addSubview:_info2];
    
    _distanceLabel = [[UILabel alloc] init];
    [_pagerView addSubview:_distanceLabel];
}

#pragma mark - TYCyclePagerViewDataSource

- (NSInteger)numberOfItemsInPagerView:(TYCyclePagerView *)pageView {
    return 30;
}

- (UICollectionViewCell *)pagerView:(TYCyclePagerView *)pagerView cellForItemAtIndex:(NSInteger)index
{
    SleepTYCyclePagerViewCell *cell = [pagerView dequeueReusableCellWithReuseIdentifier:@"sleeppagerViewcellId" forIndex:index];
    cell.button.tag = index;
    [cell updateCellWith:index];
    
    NSDictionary *dic     = [NSDictionary dictionary];
    if (index < _datas.count) {
        dic = [_datas objectAtIndex:index];
    }
    NSInteger    deeps       = [dic[@"deeps"]integerValue];
    NSInteger    lights = [dic[@"lights"]integerValue];
    NSInteger    sobers = [dic[@"sobers"]integerValue];
    NSInteger sleepTotal = deeps + lights + sobers;
    if (sleepTotal == 0) {
        cell.sleepCircle.valueDataArr = @[@"0"];
    }
    else
    {
//        if (deeps > 10) {
//            deeps = deeps - 1;
//        }
        
//        if (lights > 10) {
//            lights = lights -1;
//        }
        
        float value1 = 1.0* deeps / sleepTotal;
        float value2 = 1.0* lights / sleepTotal;
        float value3 = 1 - value1 - value2;
        NSMutableArray *array = [NSMutableArray array];
        [array addObject:[NSString stringWithFormat:@"%f",value1]];
        [array addObject:[NSString stringWithFormat:@"%f",value2]];
        [array addObject:[NSString stringWithFormat:@"%f",value3]];
        cell.sleepCircle.valueDataArr = [NSArray arrayWithArray:array];
    }
        [cell.sleepCircle startToDrawLayer];
    
        NSString *showTime = [NSString stringWithFormat:@"%d%@ %d%@",sleepTotal/60,SN_Text(@"h"),sleepTotal%60,SN_Text(@"m")];
        cell.sleepCircle.label.text = showTime;
        [cell.sleepCircle.label setAttributedText:[SN_PublicClass label1With:showTime withFontsize:12.0 withChangeText1:SN_Text(@"h") withChangeText2:SN_Text(@"m")]];
    
    [cell.button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

- (void)buttonClick:(UIButton *)sender {
    if (_currentMoveIndex < sender.tag) {
        // 右
        [_pagerView scrollToNearlyIndexAtDirection:TYPagerScrollDirectionRight animate:YES];
    }
    if (_currentMoveIndex > sender.tag) {
        // 左
        [_pagerView scrollToNearlyIndexAtDirection:TYPagerScrollDirectionLeft animate:YES];
    }
    if (_currentMoveIndex == sender.tag) {
    }
    [self updateSelectValue:sender.tag];
}

- (TYCyclePagerViewLayout *)layoutForPagerView:(TYCyclePagerView *)pageView {
    TYCyclePagerViewLayout *layout = [[TYCyclePagerViewLayout alloc]init];
    
    layout.itemSize             = CGSizeMake(CGRectGetWidth(pageView.frame)*0.85, CGRectGetHeight(pageView.frame)*0.85);
    layout.itemHorizontalCenter = YES;
    return layout;
}

- (void)pagerView:(TYCyclePagerView *)pageView didScrollFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex {
    //    NSLog(@"滑动停止 >>> %ld ->  %ld",fromIndex,toIndex);
    _currentMoveIndex = toIndex;
    [self updateSelectValue:toIndex];
}

- (void)updateSelectValue:(NSInteger)index {
    CGFloat   width     = screenWidth/ 7.0;
    NSInteger moveIndex = index;
    
    [_labelScrollView setContentOffset:CGPointMake(width*moveIndex*1.0, 0) animated:YES];
    [self buttonTitleUpdate:moveIndex];
}

@end
